package com.ptmall.app.ui.fragment;

import android.Manifest;
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.bumptech.glide.Glide;
import com.facebook.stetho.common.LogUtil;
import com.google.gson.Gson;
import com.jauker.widget.BadgeView;
import com.ptmall.app.MainActivity;
import com.ptmall.app.R;
import com.ptmall.app.base.BaseMvpFragment;
import com.ptmall.app.base.PermissionListener;
import com.ptmall.app.bean.AdvertEntity;
import com.ptmall.app.bean.HomePageArea;
import com.ptmall.app.bean.PageData;
import com.ptmall.app.bean.ProductBean;
import com.ptmall.app.bean.ShopCarBean;
import com.ptmall.app.bean.model.HomePageIndex;
import com.ptmall.app.net.HttpMethods;
import com.ptmall.app.net.api.ApiDataRepository;
import com.ptmall.app.net.api.ApiService;
import com.ptmall.app.net.base.ApiNetResponse;
import com.ptmall.app.ui.activity.CateListActivity;
import com.ptmall.app.ui.activity.GoodDetilActivity;
import com.ptmall.app.ui.activity.RqActivity;
import com.ptmall.app.ui.activity.SeachGoodActivity;
import com.ptmall.app.ui.activity.SeachXqActivity;
import com.ptmall.app.ui.activity.ShareCouponActivity;
import com.ptmall.app.ui.activity.TimeActivity;
import com.ptmall.app.ui.activity.WebActivity;
import com.ptmall.app.ui.activity.ZtActivity;
import com.ptmall.app.ui.adapter.HomePageAreaListAdapter;
import com.ptmall.app.ui.adapter.HomePageCateGoryAdapter;
import com.ptmall.app.ui.adapter.HomePageReCommendAdapter;
import com.ptmall.app.ui.adapter.HomepageTuijianAdapter;
import com.ptmall.app.ui.adapter.LikeGoodAdapter;
import com.ptmall.app.ui.adapter.NewGoodsAdapter;
import com.ptmall.app.ui.adapter.RecyCommendAdapter;
import com.ptmall.app.ui.adapter.ShareCouponAdapter;
import com.ptmall.app.utils.GlideUtil;
import com.ptmall.app.utils.LocationUtil;
import com.ptmall.app.utils.SharedPreferencesHelper;
import com.ptmall.app.view.ImageCycleView;
import com.ptmall.app.view.NoScrollGridView;
import com.ptmall.app.view.NoScrollListView;
import com.ptmall.app.view.PullScrollView;
import com.ptmall.app.view.PullToRefreshLayout;
import com.ptmall.app.view.PullableScrollView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HomePageFragment extends BaseMvpFragment {

    View view, homepage_arealist;
    double latitude, longitude;

    private String cityString;

    ApiDataRepository apiDataRepository = ApiDataRepository.getInstance();

    //商城首页
    LinearLayout homepage_bar;
    PullableScrollView homepage_scroll;
    TextView location_text,rqmore;


    //小区列表
    LinearLayout more_area;
    ImageView zt_img1, zt_img2, zt_img3, zt_img4, gocar;
    TextView homearea_locationtext, tv_zt_title1, tv_zt_by1, tv_zt_title2, tv_zt_by2, tv_zt_title3, tv_zt_by3, tv_zt_title4, tv_zt_by4;
    HomePageAreaListAdapter mHomePageAreaListAdapter;
    ListView arealist;
    List<HomePageArea> homePageAreaList = new ArrayList<>();

    //轮播图
    ImageCycleView banner_img,banner_img2;

    //分类
    NoScrollGridView index_categorygridview;
    HomePageCateGoryAdapter mHomePageCateGoryAdapter;

    //人气推荐
    RecyclerView recommendgridview;
    RecyCommendAdapter mRecyCommendAdapter;

    //新鲜水果

    NoScrollGridView likelist;
    RecyclerView tuijianlist;

    LikeGoodAdapter mLikeGoodAdapter;
    NewGoodsAdapter mHomepageTuijianAdapter;

    Intent intent;

    RelativeLayout ms_rel,tejian;

    LinearLayout zt_lin4, zt_lin3, zt_lin2, zt_lin1;

    ImageView yqyl;

    RelativeLayout seachtolist;
    SharedPreferencesHelper sharedPreferencesHelper;

    RelativeLayout rl;
    RelativeLayout rel_bag;
    private PathMeasure mPathMeasure;
    private float[] mCurrentPosition = new float[2];
    public BadgeView mBadgeView;

    private PullToRefreshLayout ptrl;
    int page = 1;
    List<ProductBean> likeArraylist = new ArrayList<>();


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_homepage, container, false);
        sharedPreferencesHelper = new SharedPreferencesHelper(getContext(), "pt");
        return view;
    }

    @Override
    public void initViews() {
        ptrl = (PullToRefreshLayout) view.findViewById(R.id.refresh_view);
        zt_lin4 = (LinearLayout) view.findViewById(R.id.zt_lin4);
        zt_lin3 = (LinearLayout) view.findViewById(R.id.zt_lin3);
        zt_lin2 = (LinearLayout) view.findViewById(R.id.zt_lin2);
        zt_lin1 = (LinearLayout) view.findViewById(R.id.zt_lin1);
        rel_bag = (RelativeLayout) view.findViewById(R.id.rel_bag);
        rl = (RelativeLayout) view.findViewById(R.id.rel);
        gocar = (ImageView) view.findViewById(R.id.gocar);
        yqyl = (ImageView) view.findViewById(R.id.yqyl);
        ms_rel = (RelativeLayout) view.findViewById(R.id.ms);
        tuijianlist = (RecyclerView) view.findViewById(R.id.tuijianlist);
        likelist = (NoScrollGridView) view.findViewById(R.id.likelist);
        location_text = (TextView) view.findViewById(R.id.location_text);
        seachtolist = (RelativeLayout) view.findViewById(R.id.seachtolist);
        homepage_arealist = view.findViewById(R.id.homepage_arealist);
        banner_img = (ImageCycleView) view.findViewById(R.id.banner_img);
        banner_img2 = (ImageCycleView) view.findViewById(R.id.banner_img2);
        arealist = (ListView) homepage_arealist.findViewById(R.id.arealist);
        index_categorygridview = (NoScrollGridView) view.findViewById(R.id.index_categorygridview);
        homepage_scroll = (PullableScrollView) view.findViewById(R.id.homepage_scroll);
        homepage_bar = (LinearLayout) view.findViewById(R.id.homepage_bar);
        recommendgridview = (RecyclerView) view.findViewById(R.id.recommendgridview);
        more_area = (LinearLayout) homepage_arealist.findViewById(R.id.more_area);
        homearea_locationtext = (TextView) homepage_arealist.findViewById(R.id.homearea_locationtext);
        tv_zt_title1 = (TextView) view.findViewById(R.id.zt_title1);
        tv_zt_by1 = (TextView) view.findViewById(R.id.zt_by1);
        rqmore = (TextView) view.findViewById(R.id.rqmore);
        zt_img1 = (ImageView) view.findViewById(R.id.zt_img1);

        tv_zt_title2 = (TextView) view.findViewById(R.id.zt_title2);
        tv_zt_by2 = (TextView) view.findViewById(R.id.zt_by2);
        zt_img2 = (ImageView) view.findViewById(R.id.zt_img2);

        tv_zt_title3 = (TextView) view.findViewById(R.id.zt_title3);
        tv_zt_by3 = (TextView) view.findViewById(R.id.zt_by3);
        zt_img3 = (ImageView) view.findViewById(R.id.zt_img3);

        tv_zt_title4 = (TextView) view.findViewById(R.id.zt_title4);
        tv_zt_by4 = (TextView) view.findViewById(R.id.zt_by4);
        zt_img4 = (ImageView) view.findViewById(R.id.zt_img4);

        tejian = (RelativeLayout) view.findViewById(R.id.tejian);

        mBadgeView = new BadgeView(getContext());
        mBadgeView.setBackground(10, 0xFFFF0000);//色
        mBadgeView.setTargetView(rel_bag);
    }

    @Override
    public void initEvents() {
        initLocation();
        mHomePageAreaListAdapter = new HomePageAreaListAdapter(getContext(), null);
        arealist.setAdapter(mHomePageAreaListAdapter);

        arealist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                location_text.setText(homePageAreaList.get(i).name);
                getHomePageIndexData();
                sharedPreferencesHelper.put("xiaoqu",homePageAreaList.get(i).name);
            }
        });
        more_area.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getContext(), SeachXqActivity.class));
            }
        });
        ms_rel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getContext(), TimeActivity.class));
            }
        });
        gocar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((MainActivity) getActivity()).mVpMain.setCurrentItem(2);
            }
        });
        yqyl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getContext(), ShareCouponActivity.class));
            }
        });
        seachtolist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                startActivity(new Intent(getContext(), SeachGoodActivity.class));
            }
        });
        location_text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAreaList();
            }
        });
        tejian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent2 = new Intent(getContext(), WebActivity.class);
                intent2.putExtra("title","勺品特荐");
                intent2.putExtra("url", HttpMethods.BASE_URL+"Detail/huodong");
                startActivity(intent2);
            }
        });
        recommendgridview.setFocusable(false);
        likelist.setFocusable(false);
        tuijianlist.setFocusable(false);
        index_categorygridview.setFocusable(false);

        mLikeGoodAdapter = new LikeGoodAdapter(getContext(), likeArraylist);
        likelist.setAdapter(mLikeGoodAdapter);
        mLikeGoodAdapter.setClickInterface(new LikeGoodAdapter.ClickInterface() {
            @Override
            public void shopcaradd(ImageView iv,int position, String id) {
                addcar(id, "1",iv);
            }
        });

        getlike();
        ptrl.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                page = 1;
                getlike();

            }

            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                page ++;
                getlike();
            }
        });
    }

    private void getlike(){
        Map<String,String> map = new HashMap<>();
        map.put("page",page+"");
        apiDataRepository.cnxh(map, new ApiNetResponse<PageData<ProductBean>>() {
            @Override
            public void onSuccess(PageData<ProductBean> data) {

                if (null != ptrl) {
                    ptrl.refreshFinish(PullToRefreshLayout.SUCCEED);
                    ptrl.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                }
                if (page == 1) {
                    likeArraylist.clear();
                }
                if (null != data.getData() && data.getData().size() > 0) {
                    likeArraylist.addAll(data.getData());
                } else {
                }
                mLikeGoodAdapter.pushData(likeArraylist);

            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (TextUtils.isEmpty(sharedPreferencesHelper.getSharedPreference("xiaoqu", "").toString())) {

            showAreaList();
        } else {
            getHomePageIndexData();
            location_text.setText(sharedPreferencesHelper.getSharedPreference("xiaoqu", "").toString());
        }
        apiDataRepository.getShopCarList(null, new ApiNetResponse<PageData<ShopCarBean>>() {
            @Override
            public void onSuccess(PageData<ShopCarBean> data) {
                mBadgeView.setText(data.getCount()+"");
            }
        });
//        location_text.setText(sharedPreferencesHelper.getSharedPreference("xiaoqu", "").toString());
    }

    public void ref() {
        if (likelist == null || recommendgridview == null) {
            return;
        }
    }

    private void initLocation() {
        requestRuntimePermisssions(new String[]{
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, new PermissionListener() {
            @Override
            public void onGranted() {
                LocationUtil.setCurrentAddress(new LocationUtil.currentAddress() {
                    @Override
                    public void getAddress(BDLocation location) {
                        if (location == null) {
                            showMsg("定位失败，请打开GPS定位功能");
                            LogUtil.d("xucc", "定位失败222");
                            return;
                        }
                        Log.d("xucc", new Gson().toJson(location));
                        if (null == cityString) {
                            cityString = location.getCity();
                        }
                        homearea_locationtext.setText("当前位置" + location.getAddress().street);
//                        location_text.setText(location.getAddress().street);
                        longitude = location.getLongitude();
                        latitude = location.getLatitude();
                        getHomePageAreaList();
                    }
                }, getContext(), true);
            }

            @Override
            public void onDenied(List<String> deniedList) {
                showMsg("定位权限获取失败");
            }
        });
    }

    private void getHomePageAreaList() {
        Map<String, String> map = new HashMap<>();
        map.put("lat", latitude + "");
        map.put("lng", longitude + "");
        apiDataRepository.homePageAreaList(map, new ApiNetResponse<PageData<HomePageArea>>() {
            @Override
            public void onSuccess(PageData<HomePageArea> data) {
                homePageAreaList = data.getData();
                mHomePageAreaListAdapter.pushData(data.getData());
            }
        });
    }

    private void getHomePageIndexData() {
        apiDataRepository.getIndex(null, new ApiNetResponse<HomePageIndex>() {
            @Override
            public void onSuccess(HomePageIndex data) {
                showShopIndex();

                showBanner(data.getSlide());
                showCateGroy(data.getStyle());
                showReCommend(data.getRenqi());
//                showFresh(data.getRenqi());

                LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
                linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
                tuijianlist.setLayoutManager(linearLayoutManager);
                mHomepageTuijianAdapter = new NewGoodsAdapter(getActivity());
                mHomepageTuijianAdapter.bind(data.getList());
                tuijianlist.setAdapter(mHomepageTuijianAdapter);
                tuijianlist.setLayoutManager(new LinearLayoutManager(getActivity()){
                    @Override
                    public boolean canScrollVertically() {
                        //解决ScrollView里存在多个RecyclerView时滑动卡顿的问题
                        //如果你的RecyclerView是水平滑动的话可以重写canScrollHorizontally方法
                        return false;
                    }
                });
                mHomepageTuijianAdapter.setClick(new NewGoodsAdapter.Click() {
                    @Override
                    public void addcarimg(ImageView iv, String id, String num) {
                        addcar(id,"1",iv);
                    }
                });
//解决数据加载不完的问题
                tuijianlist.setNestedScrollingEnabled(false);
                tuijianlist.setHasFixedSize(true);
//解决数据加载完成后, 没有停留在顶部的问题
                tuijianlist.setFocusable(false);

                likelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        Intent intent = new Intent(getContext(), GoodDetilActivity.class);
//                        intent.putExtra("id", data.getLike().get(i).productId);
                        startActivity(intent);
                    }
                });
                try {
                    tv_zt_title1.setText(data.zhuanti.get(0).title);
                    tv_zt_by1.setText(data.zhuanti.get(0).name);
                    GlideUtil.showImg(getContext(), data.zhuanti.get(0).image_index, zt_img1);
                    zt_lin1.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent(getContext(), ZtActivity.class);
                            intent.putExtra("id", data.zhuanti.get(0).zhuanId);
                            intent.putExtra("name", data.zhuanti.get(0).name);
                            intent.putExtra("title", data.zhuanti.get(0).title);
                            startActivity(intent);
                        }
                    });
                    tv_zt_title2.setText(data.zhuanti.get(1).title);
                    tv_zt_by2.setText(data.zhuanti.get(1).name);
                    GlideUtil.showImg(getContext(), data.zhuanti.get(1).image_index, zt_img2);
                    zt_lin2.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent(getContext(), ZtActivity.class);
                            intent.putExtra("id", data.zhuanti.get(1).zhuanId);
                            intent.putExtra("name", data.zhuanti.get(1).name);
                            intent.putExtra("title", data.zhuanti.get(1).title);
                            startActivity(intent);
                        }
                    });
                    tv_zt_title3.setText(data.zhuanti.get(2).title);
                    tv_zt_by3.setText(data.zhuanti.get(2).name);
                    GlideUtil.showImg(getContext(), data.zhuanti.get(2).image_index, zt_img3);
                    zt_lin3.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent(getContext(), ZtActivity.class);
                            intent.putExtra("id", data.zhuanti.get(2).zhuanId);
                            intent.putExtra("name", data.zhuanti.get(2).name);
                            intent.putExtra("title", data.zhuanti.get(2).title);
                            startActivity(intent);
                        }
                    });
                    tv_zt_title4.setText(data.zhuanti.get(3).title);
                    tv_zt_by4.setText(data.zhuanti.get(3).name);
                    GlideUtil.showImg(getContext(), data.zhuanti.get(3).image_index, zt_img4);
                    zt_lin4.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent(getContext(), ZtActivity.class);
                            intent.putExtra("id", data.zhuanti.get(3).zhuanId);
                            intent.putExtra("name", data.zhuanti.get(3).name);
                            intent.putExtra("title", data.zhuanti.get(3).title);
                            startActivity(intent);
                        }
                    });
                } catch (Exception e) {

                }


            }
        });
    }

    private void addcar(String id, String num,ImageView iv) {
        Map<String, String> map = new HashMap<>();
        map.put("productId", id);
        map.put("num", num);
        apiDataRepository.addShopCar(map, new ApiNetResponse<Object>() {
            @Override
            public void onSuccess(Object data) {
                showMsg("加入购物车成功");
                ((MainActivity)getActivity()).mShopCarfragment.getData();
                addCartStart(iv);
            }
        });
    }

    private void showShopIndex() {
        homepage_arealist.setVisibility(View.GONE);
        homepage_bar.setVisibility(View.VISIBLE);
        homepage_scroll.setVisibility(View.VISIBLE);
    }

    private void showAreaList() {
        homepage_arealist.setVisibility(View.VISIBLE);
        homepage_bar.setVisibility(View.GONE);
        homepage_scroll.setVisibility(View.GONE);
    }


    public void showBanner(List<HomePageIndex.SlideBean> banners) {
        if (banners == null || banners.size() < 1) {
            return;
        }
        banner_img.setImageResources(banners, new ImageCycleView.ImageCycleViewListener() {
            @Override
            public void displayImage(String imageURL, ImageView imageView) {
                //根据图片地址，设置imageView
                // 使用ImageLoader对图片进行加装！
//                GlideUtil.showImg(getActivity(), imageURL, imageView);
                Glide.with(getActivity()).load(HttpMethods.BASEIMG_URL+imageURL).dontAnimate().placeholder(R.drawable.z1).error(R.drawable.z1).into(imageView);

            }

            @Override
            public void onImageClick(HomePageIndex.SlideBean mEntity, int postion, View imageView) {
                if (banners.get(postion).href_type.equals("1")) {
                    Intent intent = new Intent(getContext(), WebActivity.class);
                    intent.putExtra("title", "活动详情");
                    intent.putExtra("url", HttpMethods.BASE_URL + "Detail/slide/slideId/" + banners.get(postion).slideId);
                    startActivity(intent);
                } else if(banners.get(postion).href_type.equals("2")){
                    Intent intent = new Intent(getContext(), GoodDetilActivity.class);
                    intent.putExtra("id", banners.get(postion).productId);
                    startActivity(intent);
                } else if(banners.get(postion).href_type.equals("3")){
                    Intent intent = new Intent(getContext(), CateListActivity.class);
                    intent.putExtra("id", banners.get(postion).styleId);
                    startActivity(intent);
                }

            }
        });
        banner_img2.setImageResources(banners, new ImageCycleView.ImageCycleViewListener() {
            @Override
            public void displayImage(String imageURL, ImageView imageView) {
                //根据图片地址，设置imageView
                // 使用ImageLoader对图片进行加装！
                GlideUtil.showImg(getActivity(), imageURL, imageView);
            }

            @Override
            public void onImageClick(HomePageIndex.SlideBean mEntity, int postion, View imageView) {
                if (banners.get(postion).href_type.equals("1")) {
                    Intent intent = new Intent(getContext(), WebActivity.class);
                    intent.putExtra("title", "活动详情");
                    intent.putExtra("url", HttpMethods.BASE_URL + "Detail/slide/slideId/" + banners.get(postion).slideId);
                    startActivity(intent);
                } else if(banners.get(postion).href_type.equals("2")){
                    Intent intent = new Intent(getContext(), GoodDetilActivity.class);
                    intent.putExtra("id", banners.get(postion).productId);
                    startActivity(intent);
                } else if(banners.get(postion).href_type.equals("3")){
                    Intent intent = new Intent(getContext(), CateListActivity.class);
                    intent.putExtra("id", banners.get(postion).styleId);
                    startActivity(intent);
                }

            }
        });
    }

    private void showCateGroy(List<HomePageIndex.StyleBean> list) {
        mHomePageCateGoryAdapter = new HomePageCateGoryAdapter(getContext(), list);
        index_categorygridview.setAdapter(mHomePageCateGoryAdapter);
        index_categorygridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                intent = new Intent(getContext(), CateListActivity.class);
                intent.putExtra("id", list.get(i).getStyleId());
                startActivity(intent);
            }
        });
    }

    private void showReCommend(List<ProductBean> list) {
        mRecyCommendAdapter = new RecyCommendAdapter(getActivity());
        mRecyCommendAdapter.bind(list);
        recommendgridview.setAdapter(mRecyCommendAdapter);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recommendgridview.setLayoutManager(linearLayoutManager);
        rqmore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent = new Intent(getContext(), RqActivity.class);
                intent.putExtra("list", (Serializable) list);
                startActivity(intent);
            }
        });
        mRecyCommendAdapter.setClick(new RecyCommendAdapter.Click() {
            @Override
            public void addcars(ImageView iv, String id, String num) {
                addcar(id,num,iv);
            }
        });
    }

//    private void showFresh(List<ProductBean> list) {
//        mHomePageReCommendAdapter = new HomePageReCommendAdapter(getContext(), list);
//        recommendgridview.setAdapter(mHomePageReCommendAdapter);
//        recommendgridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                Intent intent = new Intent(getContext(), GoodDetilActivity.class);
//                intent.putExtra("id", list.get(i).productId);
//                startActivity(intent);
//            }
//        });
//    }
    /**
     * ★★★★★把商品添加到购物车的动画效果★★★★★
     * @param iv
     */
    private void addCartStart( ImageView iv) {
//      一、创造出执行动画的主题---imageview
        //代码new一个imageview，图片资源是上面的imageview的图片
        // (这个图片就是执行动画的图片，从开始位置出发，经过一个抛物线（贝塞尔曲线），移动到购物车里)
        final ImageView goods = new ImageView(getContext());
        goods.setImageDrawable(iv.getDrawable());
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(100, 100);
        rl.addView(goods, params);

//        二、计算动画开始/结束点的坐标的准备工作
        //得到父布局的起始点坐标（用于辅助计算动画开始/结束时的点的坐标）
        int[] parentLocation = new int[2];
        rl.getLocationInWindow(parentLocation);

        //得到商品图片的坐标（用于计算动画开始的坐标）
        int startLoc[] = new int[2];
        iv.getLocationInWindow(startLoc);

        //得到购物车图片的坐标(用于计算动画结束后的坐标)
        int endLoc[] = new int[2];
        endLoc[0] = getView().getWidth()/8*4;
        endLoc[1] = getView().getHeight()-50;
//        car.getLocationInWindow(endLoc);


//        三、正式开始计算动画开始/结束的坐标
        //开始掉落的商品的起始点：商品起始点-父布局起始点+该商品图片的一半
        float startX = startLoc[0] - parentLocation[0] + iv.getWidth() / 2;
        float startY = startLoc[1] - parentLocation[1] + iv.getHeight() / 2;

        //商品掉落后的终点坐标：购物车起始点-父布局起始点+购物车图片的1/5
        float toX = endLoc[0] - parentLocation[0];
        float toY = endLoc[1] - parentLocation[1];
        Log.i("location ====","endLoc[]" + endLoc[0] + "  " + endLoc[1]);
        Log.i("location ====","toX[]" + toX + " toY " + toY);
//        四、计算中间动画的插值坐标（贝塞尔曲线）（其实就是用贝塞尔曲线来完成起终点的过程）
        //开始绘制贝塞尔曲线
        Path path = new Path();
        //移动到起始点（贝塞尔曲线的起点）
        path.moveTo(startX, startY);
        //使用二次萨贝尔曲线：注意第一个起始坐标越大，贝塞尔曲线的横向距离就会越大，一般按照下面的式子取即可
        path.quadTo((startX + toX) / 2, startY, toX, toY);
        //mPathMeasure用来计算贝塞尔曲线的曲线长度和贝塞尔曲线中间插值的坐标，
        // 如果是true，path会形成一个闭环
        mPathMeasure = new PathMeasure(path, false);

        //★★★属性动画实现（从0到贝塞尔曲线的长度之间进行插值计算，获取中间过程的距离值）
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, mPathMeasure.getLength());
        valueAnimator.setDuration(500);
        // 匀速线性插值器
        valueAnimator.setInterpolator(new LinearInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                // 当插值计算进行时，获取中间的每个值，
                // 这里这个值是中间过程中的曲线长度（下面根据这个值来得出中间点的坐标值）
                float value = (Float) animation.getAnimatedValue();
                // ★★★★★获取当前点坐标封装到mCurrentPosition
                // boolean getPosTan(float distance, float[] pos, float[] tan) ：
                // 传入一个距离distance(0<=distance<=getLength())，然后会计算当前距
                // 离的坐标点和切线，pos会自动填充上坐标，这个方法很重要。
                mPathMeasure.getPosTan(value, mCurrentPosition, null);//mCurrentPosition此时就是中间距离点的坐标值
                // 移动的商品图片（动画图片）的坐标设置为该中间点的坐标
                goods.setTranslationX(mCurrentPosition[0]);
                goods.setTranslationY(mCurrentPosition[1]);
            }
        });
//      五、 开始执行动画
        valueAnimator.start();

//      六、动画结束后的处理
        valueAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            //当动画结束后：
            @Override
            public void onAnimationEnd(Animator animation) {
                rl.removeView(goods);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
    }


    private void startPropertyAnim(ImageView iv) {
        // 灏嗕竴涓猅extView娌垮瀭鐩存柟鍚戝厛浠庡師澶у皬锛?f锛夋斁澶у埌5鍊嶅ぇ灏忥紙5f锛夛紝鐒跺悗鍐嶅彉鍥炲師澶у皬銆?

        ObjectAnimator scaleX = ObjectAnimator.ofFloat(iv, "scaleX", 0.5f, 1f);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(iv, "scaleY", 0.5f, 1f);

        scaleX.setDuration(300);
        scaleY.setDuration(300);

        // 鍥炶皟鐩戝惉锛屽彲浠ユ湁涔熷彲浠ユ棤銆?
        // 鏍规嵁鎯呭喌锛屽鏋滈渶瑕佺洃鍚姩鐢绘墽琛屽埌浣曠鈥滆繘搴︹€濓紝閭ｄ箞灏辩洃鍚箣銆?
//        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
//
//            @Override
//            public void onAnimationUpdate(ValueAnimator animation) {
//                float value = (Float) animation.getAnimatedValue();
//            }
//        });

        // 姝ｅ紡寮€濮嬪惎鍔ㄦ墽琛屽姩鐢?

        scaleX.start();
        scaleY.start();
    }


}
